#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db.models import Q
from django.db import connection
from web.manager.log_manager import LogManager
from web.constants.datetime_format import DatetimeFormat
from web.constants.rollover_type import RolloverType
from web.models.robot8_account import Robot8Account
from web.models.robot8_commodity_future_transaction_record import Robot8CommodityFutureTransactionRecord
from web.models.robot8_commodity_future_filter import Robot8CommodityFutureFilter
from web.models.robot8_commodity_future_rollover import Robot8CommodityFutureRollover
from web.models.commodity_future_date_contract_data import CommodityFutureDateContractData
from web.models.commodity_future_info import CommodityFutureInfo
from web.models.model_commodity_future_date_data_macd_gold_cross import ModelCommodityFutureDateDataMACDGoldCross
from web.models.model_commodity_future_date_data_macd_dead_cross import ModelCommodityFutureDateDataMACDDeadCross
from web.models.model_commodity_future_date_data_close_price_ma5_gold_cross import \
    ModelCommodityFutureDateDataClosePriceMA5GoldCross
from web.models.model_commodity_future_date_data_close_price_ma5_dead_cross import \
    ModelCommodityFutureDateDataClosePriceMA5DeadCross
from web.models.model_commodity_future_date_data_hei_kin_ashi_up import ModelCommodityFutureDateDataHeiKinAshiUp
from web.models.model_commodity_future_date_data_hei_kin_ashi_down import ModelCommodityFutureDateDataHeiKinAshiDown
from web.models.model_commodity_future_date_data_kd_gold_cross import ModelCommodityFutureDateDataKDGoldCross
from web.models.model_commodity_future_date_data_kd_dead_cross import ModelCommodityFutureDateDataKDDeadCross
from web.dao.base_dao import BaseDao
from web.config.robot8_config import Robot8Config
from web.util.fee_util import FeeUtil
from web.util.datetime_util import DatetimeUtil
from web.util.char_util import CharUtil
from web.constants.direction import Direction
from web.constants.filter_type import FilterType

Logger = LogManager.get_logger(__name__)

class Robot8CommodityFutureTransactionRecordDao(BaseDao):
    """
    Robot8CommodityFutureTransactionRecord的dao类
    """

    model_class = Robot8CommodityFutureTransactionRecord

    def rollover_for_close(self, current_transaction_date):
        """
        移仓换月：平仓
        """

        Logger.info("移仓换月：平仓，交易日期为：" + str(current_transaction_date))

        # 获取所有账户信息
        robot8_account_queryset = Robot8Account.objects.all()
        for robot8_account in robot8_account_queryset:
            if robot8_account.hold_commodity_future_number == 0:
                Logger.info("账号[" + str(robot8_account.robot_name) + "]持期货的数量为0，不需要期货平仓")
                continue

            # 某个机器人账户的期货持仓的交易记录
            robot8_commodity_future_transaction_record_queryset = Robot8CommodityFutureTransactionRecord.objects.filter(
                Q(robot_name=robot8_account.robot_name)
                & ((Q(direction=1) & Q(sell_date__isnull=True) & Q(sell_price__isnull=True) & Q(
                    sell_lot__isnull=True))
                   | (Q(direction=-1) & Q(buy_date__isnull=True) & Q(buy_price__isnull=True) & Q(
                            buy_lot__isnull=True))))

            if robot8_commodity_future_transaction_record_queryset == None or len(
                    robot8_commodity_future_transaction_record_queryset) == 0:
                Logger.info("账号[" + str(robot8_account.robot_name) + "，在日期[" + str(
                    current_transaction_date) + "]持期货的数量为0，不需要期货平仓")
                continue

            for robot8_commodity_future_transaction_record in robot8_commodity_future_transaction_record_queryset:

                with connection.cursor() as cursor:
                    # 下一个交易日
                    cursor.execute("select * from (select * from c_f_date_contract_data t "
                                   "where t.code=%s and t.transaction_date>to_date(%s,'yyyy-mm-dd') "
                                   "order by t.transaction_date asc) "
                                   "where rownum<=1",
                                   [robot8_commodity_future_transaction_record.code,
                                    DatetimeUtil.datetime_to_str(current_transaction_date,
                                                                 DatetimeFormat.Date_Format_With_Line)])
                    next_commodity_future_date_data_tuple = cursor.fetchone()

                    # 判断下一个交易日是否是新合约
                    cursor.execute("select cfdd.* from c_f_date_contract_data cfdd "
                                   "join commodity_future_info cfi on cfi.code=FNC_EXTRACT_CONTRACT_CODE(cfdd.code) "
                                   "and cfdd.price_change<-cfi.price_limit*100 "
                                   "where cfdd.code=%s and cfdd.transaction_date=to_date(%s,'yyyy-mm-dd') "
                                   "union "
                                   "select cfdd.* from commodity_future_date_data cfdd "
                                   "join commodity_future_info cfi on cfi.code=FNC_EXTRACT_CONTRACT_CODE(cfdd.code) "
                                   "and cfdd.price_change>cfi.price_limit*100 "
                                   "where cfdd.code=%s and cfdd.transaction_date=to_date(%s,'yyyy-mm-dd')",
                                   [robot8_commodity_future_transaction_record.code,
                                    DatetimeUtil.datetime_to_str(next_commodity_future_date_data_tuple[2],
                                                                 DatetimeFormat.Date_Format_With_Line),
                                    robot8_commodity_future_transaction_record.code,
                                    DatetimeUtil.datetime_to_str(next_commodity_future_date_data_tuple[2],
                                                                 DatetimeFormat.Date_Format_With_Line)])
                    first_commodity_future_date_data_tuple = cursor.fetchone()

                    # 如果下一个交易日是新合约，则现在开始移仓换月
                    if first_commodity_future_date_data_tuple != None and len(first_commodity_future_date_data_tuple) != 0:
                        # 在robot8_commodity_future_rollover表中插入记录
                        robot8_commodity_future_rollover = Robot8CommodityFutureRollover()
                        robot8_commodity_future_rollover.code = robot8_commodity_future_transaction_record.code
                        robot8_commodity_future_rollover.robot_name = robot8_commodity_future_transaction_record.robot_name
                        robot8_commodity_future_rollover.final_transaction_date = current_transaction_date
                        robot8_commodity_future_rollover.direction = robot8_commodity_future_transaction_record.direction
                        robot8_commodity_future_rollover.filter_type = robot8_commodity_future_transaction_record.filter_type
                        robot8_commodity_future_rollover.save()

                        # 更新robot8_c_f_transact_record表
                        # 当前交易日
                        current_commodity_future_date_contract_data = CommodityFutureDateContractData.objects.get(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(transaction_date=current_transaction_date))
                        commodity_future_info = CommodityFutureInfo.objects.get(code=CharUtil.extract_alpha(robot8_commodity_future_transaction_record.code))
                        if robot8_commodity_future_transaction_record.direction == Direction.Up:
                            robot8_commodity_future_transaction_record.sell_date = current_transaction_date
                            robot8_commodity_future_transaction_record.sell_price = current_commodity_future_date_contract_data.close_price
                            robot8_commodity_future_transaction_record.sell_lot = robot8_commodity_future_transaction_record.buy_lot
                            robot8_commodity_future_rollover.direction = Direction.Up
                            robot8_commodity_future_rollover.filter_type = robot8_commodity_future_transaction_record.filter_type
                            robot8_commodity_future_transaction_record.close_commission = FeeUtil.calculate_close_old_commodity_future_fee(
                                current_commodity_future_date_contract_data.close_price, commodity_future_info,
                                robot8_commodity_future_transaction_record.sell_lot)
                            robot8_commodity_future_transaction_record.profit_and_loss = float(
                                robot8_commodity_future_transaction_record.sell_price) * float(
                                robot8_commodity_future_transaction_record.sell_lot) * float(
                                commodity_future_info.transaction_multiplier) - float(
                                robot8_commodity_future_transaction_record.buy_price) * float(
                                robot8_commodity_future_transaction_record.buy_lot) * float(
                                commodity_future_info.transaction_multiplier)
                            robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                                robot8_commodity_future_transaction_record.profit_and_loss) / (float(
                                robot8_commodity_future_transaction_record.buy_price) * float(
                                robot8_commodity_future_transaction_record.buy_lot) * float(
                                commodity_future_info.transaction_multiplier) * float(
                                commodity_future_info.company_deposit)) * 100
                            self.update(robot8_commodity_future_transaction_record)
                        if robot8_commodity_future_transaction_record.direction == Direction.Down:
                            robot8_commodity_future_transaction_record.buy_date = current_transaction_date
                            robot8_commodity_future_transaction_record.buy_price = current_commodity_future_date_contract_data.close_price
                            robot8_commodity_future_transaction_record.buy_lot = robot8_commodity_future_transaction_record.sell_lot
                            robot8_commodity_future_rollover.direction = Direction.Down
                            robot8_commodity_future_rollover.filter_type = robot8_commodity_future_transaction_record.filter_type
                            robot8_commodity_future_transaction_record.close_commission = FeeUtil.calculate_close_old_commodity_future_fee(
                                current_commodity_future_date_contract_data.close_price, commodity_future_info,
                                robot8_commodity_future_transaction_record.buy_lot)
                            robot8_commodity_future_transaction_record.profit_and_loss = float(
                                robot8_commodity_future_transaction_record.sell_price) * float(
                                robot8_commodity_future_transaction_record.sell_lot) * float(
                                commodity_future_info.transaction_multiplier) - float(
                                robot8_commodity_future_transaction_record.buy_price) * float(
                                robot8_commodity_future_transaction_record.buy_lot) * float(
                                commodity_future_info.transaction_multiplier)
                            robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                                robot8_commodity_future_transaction_record.profit_and_loss) / (float(
                                robot8_commodity_future_transaction_record.sell_price) * float(
                                robot8_commodity_future_transaction_record.sell_lot) * float(
                                commodity_future_info.transaction_multiplier) * float(
                                commodity_future_info.company_deposit)) * 100
                            self.update(robot8_commodity_future_transaction_record)

    def sell_or_buy(self, current_transaction_date, mandatoryStopLoss, mandatoryStopLossRate):
        """
        期货平仓
        """

        Logger.info("期货平仓，交易日期为：" + str(current_transaction_date))

        # 获取所有账户信息
        robot8_account_queryset = Robot8Account.objects.all()
        for robot8_account in robot8_account_queryset:
            if robot8_account.hold_commodity_future_number == 0:
                Logger.info("账号[" + str(robot8_account.robot_name) + "]持期货的数量为0，不需要期货平仓")
                continue

            # 某个机器人账户的期货持仓的交易记录
            robot8_commodity_future_transaction_record_queryset = Robot8CommodityFutureTransactionRecord.objects.filter(
                Q(robot_name=robot8_account.robot_name)
                & ((Q(direction=1) & Q(sell_date__isnull=True) & Q(sell_price__isnull=True) & Q(
                    sell_lot__isnull=True))
                   | (Q(direction=-1) & Q(buy_date__isnull=True) & Q(buy_price__isnull=True) & Q(
                            buy_lot__isnull=True))))

            if robot8_commodity_future_transaction_record_queryset == None or len(
                    robot8_commodity_future_transaction_record_queryset) == 0:
                Logger.info("账号[" + str(robot8_account.robot_name) + "，在日期[" + str(
                    current_transaction_date) + "]持期货的数量为0，不需要期货平仓")
                continue

            for robot8_commodity_future_transaction_record in robot8_commodity_future_transaction_record_queryset:
                # 查询这个期货的信息
                commodity_future_info = CommodityFutureInfo.objects.get(
                    code=CharUtil.extract_alpha(robot8_commodity_future_transaction_record.code))

                # 是否平仓。true表示准备平仓，false表示不准备平仓
                do_sell_or_buy = False

                commodity_future_date_contract_data = None
                commodity_future_date_contract_data_queryset = CommodityFutureDateContractData.objects.filter(
                    Q(code=CharUtil.extract_alpha(robot8_commodity_future_transaction_record.code)) & Q(
                        transaction_date=current_transaction_date))
                # 如果没有查找到记录，可能是因为这个期货在这个交易日停牌，因此跳过这条记录
                if commodity_future_date_contract_data_queryset == None or len(commodity_future_date_contract_data_queryset) == 0:
                    Logger.info("期货[" + robot8_commodity_future_transaction_record.code + "]在日期[" +
                                str(current_transaction_date) + "]没有查找到记录，可能是因为这个股票在这个交易日停牌，因此跳过这条记录")
                    continue
                else:
                    commodity_future_date_contract_data = commodity_future_date_contract_data_queryset[0]

                # 如果这只期货做多，并且当天出现下跌，则平仓
                if robot8_commodity_future_transaction_record.direction == Direction.Up and Robot8Config.Transaction_Strategy == 1 and commodity_future_date_contract_data.price_change < 0:
                    Logger.info("期货[" + robot8_commodity_future_transaction_record.code + "]做多，并且在日期[" +
                                DatetimeUtil.datetime_to_str(current_transaction_date) + "]下跌了[" + str(
                        commodity_future_date_contract_data.price_change) +
                                "]，因此被平仓")
                    do_sell_or_buy = True
                # 如果这只期货做空，并且当天出现上涨，则平仓
                if robot8_commodity_future_transaction_record.direction == Direction.Down and Robot8Config.Transaction_Strategy == 1 and commodity_future_date_contract_data.price_change > 0:
                    Logger.info("期货[" + robot8_commodity_future_transaction_record.code + "]做空，并且在日期[" +
                                DatetimeUtil.datetime_to_str(current_transaction_date) + "]上涨了[" + str(
                        commodity_future_date_contract_data.price_change) +
                                "]，因此被平仓")
                    do_sell_or_buy = True

                # 平仓价格，用于判断是否强制止损
                sell_price_for_mandatory_stop = float(0)
                # 判断是否有强制止损
                if Robot8Config.Mandatory_Stop_Loss == True:

                    current_close_price_queryset = CommodityFutureDateContractData.objects.values('close_price').filter(
                        Q(code=robot8_commodity_future_transaction_record.code) & Q(
                            transaction_date=current_transaction_date))
                    sell_price_for_mandatory_stop = current_close_price_queryset[0]['close_price']

                    if sell_price_for_mandatory_stop == 0:
                        # 说明期货在这一天没有交易记录
                        Logger.info("期货[" + robot8_commodity_future_transaction_record.code + "]在日期[" +
                                    str(current_transaction_date) + "]没有交易记录")
                    else:
                        # 损失率
                        loss_rate = float(0)
                        if robot8_commodity_future_transaction_record.direction == Direction.Up:
                            loss_rate = (sell_price_for_mandatory_stop - robot8_commodity_future_transaction_record.buy_price) / robot8_commodity_future_transaction_record.buy_price * 100
                        if robot8_commodity_future_transaction_record.direction == Direction.Down:
                            loss_rate = (robot8_commodity_future_transaction_record.sell_price - sell_price_for_mandatory_stop) / robot8_commodity_future_transaction_record.sell_price * 100
                        if loss_rate <= -Robot8Config.Mandatory_Stop_Loss_Rate:
                            Logger.info("期货[" + robot8_commodity_future_transaction_record.code + "]在日期[" +
                                        str(current_transaction_date) + "]损失超过了[" + str(loss_rate) + "]，因此被强制止损")

                        if robot8_commodity_future_transaction_record.direction == Direction.Up:
                            # 更新robot8_c_f_transact_record表的sell_date、sell_price、sell_amount、profit_and_loss和profit_and_loss_rate字段
                            robot8_commodity_future_transaction_record.sell_date = current_transaction_date
                            robot8_commodity_future_transaction_record.sell_price = sell_price_for_mandatory_stop
                            robot8_commodity_future_transaction_record.sell_lot = robot8_commodity_future_transaction_record.buy_lot
                            robot8_commodity_future_transaction_record.close_commission = FeeUtil.calculate_close_old_commodity_future_fee(
                                sell_price_for_mandatory_stop, commodity_future_info,
                                robot8_commodity_future_transaction_record.sell_lot)
                            robot8_commodity_future_transaction_record.profit_and_loss = float(
                                robot8_commodity_future_transaction_record.sell_price) * float(
                                robot8_commodity_future_transaction_record.sell_lot) * float(
                                commodity_future_info.transaction_multiplier) - float(
                                robot8_commodity_future_transaction_record.buy_price) * float(
                                robot8_commodity_future_transaction_record.buy_lot) * float(
                                commodity_future_info.transaction_multiplier)
                            robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                                robot8_commodity_future_transaction_record.profit_and_loss) / (float(
                                robot8_commodity_future_transaction_record.buy_price) * float(
                                robot8_commodity_future_transaction_record.buy_lot) * float(
                                commodity_future_info.transaction_multiplier) * float(
                                commodity_future_info.company_deposit)) * 100
                            # robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                            #     robot8_commodity_future_transaction_record.profit_and_loss) / float(
                            #     robot8_commodity_future_transaction_record.buy_price) / float(
                            #     commodity_future_info.company_deposit) * 100
                            self.update(robot8_commodity_future_transaction_record)

                        if robot8_commodity_future_transaction_record.direction == Direction.Down:
                            # 更新robot8_c_f_transact_record表的buy_date、buy_price、buy_amount、profit_and_loss和profit_and_loss_rate字段
                            robot8_commodity_future_transaction_record.buy_date = current_transaction_date
                            robot8_commodity_future_transaction_record.buy_price = sell_price_for_mandatory_stop
                            robot8_commodity_future_transaction_record.buy_lot = robot8_commodity_future_transaction_record.sell_lot
                            robot8_commodity_future_transaction_record.close_commission = FeeUtil.calculate_close_old_commodity_future_fee(
                                sell_price_for_mandatory_stop, commodity_future_info,
                                robot8_commodity_future_transaction_record.buy_lot)
                            robot8_commodity_future_transaction_record.profit_and_loss = float(
                                robot8_commodity_future_transaction_record.sell_price) * float(
                                robot8_commodity_future_transaction_record.sell_lot) * float(
                                commodity_future_info.transaction_multiplier) - float(
                                robot8_commodity_future_transaction_record.buy_price) * float(
                                robot8_commodity_future_transaction_record.buy_lot) * float(
                                commodity_future_info.transaction_multiplier)
                            robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                                robot8_commodity_future_transaction_record.profit_and_loss) / (float(
                                robot8_commodity_future_transaction_record.sell_price) * float(
                                robot8_commodity_future_transaction_record.sell_lot) * float(
                                commodity_future_info.transaction_multiplier) * float(
                                commodity_future_info.company_deposit)) * 100
                            # robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                            #     robot8_commodity_future_transaction_record.profit_and_loss) / float(
                            #     robot8_commodity_future_transaction_record.sell_price) / float(
                            #     commodity_future_info.company_deposit) * 100
                            # robot8_commodity_future_transaction_record.close_commission = FeeUtil.calculate_close_old_commodity_future_fee(
                            #     sell_price_for_mandatory_stop, commodity_future_info,
                            #     robot8_commodity_future_transaction_record.buy_lot)
                            self.update(robot8_commodity_future_transaction_record)

                    continue

                # 判断是否是死叉/金叉，如果不是死叉/金叉，则返回下一条记录
                sell_or_buy_price = float(0)
                # MACD金叉
                if robot8_commodity_future_transaction_record.filter_type == FilterType.MACD_Gold_Cross:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_macd_gold_cross_queryset = ModelCommodityFutureDateDataMACDGoldCross.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                sell_date=current_transaction_date))
                        if model_commodity_future_date_data_macd_gold_cross_queryset is not None and len(
                                model_commodity_future_date_data_macd_gold_cross_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_macd_gold_cross_queryset[0].sell_price
                            do_sell_or_buy = True
                # MACD死叉
                if robot8_commodity_future_transaction_record.filter_type == FilterType.MACD_Dead_Cross:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_macd_dead_cross_queryset = ModelCommodityFutureDateDataMACDDeadCross.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                buy_date=current_transaction_date))
                        if model_commodity_future_date_data_macd_dead_cross_queryset is not None and len(
                                model_commodity_future_date_data_macd_dead_cross_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_macd_dead_cross_queryset[0].buy_price
                            do_sell_or_buy = True
                # 收盘价金叉五日均线
                if robot8_commodity_future_transaction_record.filter_type == FilterType.Close_Price_Ma5_Gold_Cross:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_close_price_ma5_gold_cross_queryset = ModelCommodityFutureDateDataClosePriceMA5GoldCross.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                sell_date=current_transaction_date))
                        if model_commodity_future_date_data_close_price_ma5_gold_cross_queryset is not None and len(
                                model_commodity_future_date_data_close_price_ma5_gold_cross_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_close_price_ma5_gold_cross_queryset[
                                0].sell_price
                            do_sell_or_buy = True
                # 收盘价死叉五日均线
                if robot8_commodity_future_transaction_record.filter_type == FilterType.Close_Price_Ma5_Dead_Cross:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_close_price_ma5_dead_cross_queryset = ModelCommodityFutureDateDataClosePriceMA5DeadCross.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                buy_date=current_transaction_date))
                        if model_commodity_future_date_data_close_price_ma5_dead_cross_queryset is not None and len(
                                model_commodity_future_date_data_close_price_ma5_dead_cross_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_close_price_ma5_dead_cross_queryset[
                                0].buy_price
                            do_sell_or_buy = True
                # 平均K线是否从下跌趋势变为上涨趋势
                if robot8_commodity_future_transaction_record.filter_type == FilterType.Hei_Kin_Ashi_Up:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_hei_kin_ashi_up_queryset = ModelCommodityFutureDateDataHeiKinAshiUp.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                sell_date=current_transaction_date))
                        if model_commodity_future_date_data_hei_kin_ashi_up_queryset is not None and len(
                                model_commodity_future_date_data_hei_kin_ashi_up_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_hei_kin_ashi_up_queryset[0].sell_price
                            do_sell_or_buy = True
                # 平均K线是否从下跌趋势变为上涨趋势
                if robot8_commodity_future_transaction_record.filter_type == FilterType.Hei_Kin_Ashi_Down:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_hei_kin_ashi_down_queryset = ModelCommodityFutureDateDataHeiKinAshiDown.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                buy_date=current_transaction_date))
                        if model_commodity_future_date_data_hei_kin_ashi_down_queryset is not None and len(
                                model_commodity_future_date_data_hei_kin_ashi_down_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_hei_kin_ashi_down_queryset[0].buy_price
                            do_sell_or_buy = True
                # KD金叉
                if robot8_commodity_future_transaction_record.filter_type == FilterType.KD_Gold_Cross:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_kd_gold_cross_queryset = ModelCommodityFutureDateDataKDGoldCross.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                sell_date=current_transaction_date))
                        if model_commodity_future_date_data_kd_gold_cross_queryset is not None and len(
                                model_commodity_future_date_data_kd_gold_cross_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_kd_gold_cross_queryset[0].sell_price
                            do_sell_or_buy = True
                # KD死叉
                if robot8_commodity_future_transaction_record.filter_type == FilterType.KD_Dead_Cross:
                    if Robot8Config.Transaction_Strategy == 2:
                        model_commodity_future_date_data_kd_dead_cross_queryset = ModelCommodityFutureDateDataKDDeadCross.objects.filter(
                            Q(code=robot8_commodity_future_transaction_record.code) & Q(
                                buy_date=current_transaction_date))
                        if model_commodity_future_date_data_kd_dead_cross_queryset is not None and len(
                                model_commodity_future_date_data_kd_dead_cross_queryset) != 0:
                            sell_or_buy_price = model_commodity_future_date_data_kd_dead_cross_queryset[0].buy_price
                            do_sell_or_buy = True

                # 无论第二天是涨是跌，全部卖出
                if Robot8Config.Transaction_Strategy == 3:
                    Logger.info("股票[" + robot8_commodity_future_transaction_record.code + "]，无论第二天是涨是跌，全部卖出")
                    do_sell_or_buy = True

                # 判断是否是死叉，如果不是死叉，则返回下一条记录。收盘价金叉死叉牛熊线算法
                if Robot8Config.Transaction_Strategy == 4:
                    commodity_future_date_contract_data_queryset = CommodityFutureDateContractData.objects.filter(
                        Q(transaction_date=current_transaction_date) & Q(code=robot8_commodity_future_transaction_record.code))
                    if commodity_future_date_contract_data_queryset == None or len(commodity_future_date_contract_data_queryset) == 0:
                        Logger.info("期货[" + robot8_commodity_future_transaction_record.code + "]在日期[" + str(
                            current_transaction_date) + "]没有交易记录，跳过")
                        continue
                    commodity_future_date_contract_data = commodity_future_date_contract_data_queryset[0]
                    # 牛熊线
                    bull_short_line = None
                    if commodity_future_date_contract_data.ma250 != None and commodity_future_date_contract_data.bias250 <= Robot8Config.Bias_Threshold_Top \
                            and commodity_future_date_contract_data.bias250 >= Robot8Config.Bias_Threshold_Bottom:
                        bull_short_line = commodity_future_date_contract_data.ma250
                    if commodity_future_date_contract_data.ma120 != None and commodity_future_date_contract_data.bias120 <= Robot8Config.Bias_Threshold_Top \
                            and commodity_future_date_contract_data.bias120 >= Robot8Config.Bias_Threshold_Bottom:
                        bull_short_line = commodity_future_date_contract_data.ma120
                    if commodity_future_date_contract_data.ma60 != None and commodity_future_date_contract_data.bias60 <= Robot8Config.Bias_Threshold_Top \
                            and commodity_future_date_data.bias60 >= Robot8Config.Bias_Threshold_Bottom:
                        bull_short_line = commodity_future_date_contract_data.ma60
                    if commodity_future_date_contract_data.ma20 != None and commodity_future_date_contract_data.bias20 <= Robot8Config.Bias_Threshold_Top \
                            and commodity_future_date_contract_data.bias20 >= Robot8Config.Bias_Threshold_Bottom:
                        bull_short_line = commodity_future_date_contract_data.ma20
                    if commodity_future_date_contract_data.ma10 != None and commodity_future_date_contract_data.bias10 <= Robot8Config.Bias_Threshold_Top \
                            and commodity_future_date_contract_data.bias10 >= Robot8Config.Bias_Threshold_Bottom:
                        bull_short_line = commodity_future_date_contract_data.ma10
                    if commodity_future_date_contract_data.ma5 != None and commodity_future_date_contract_data.bias5 <= Robot8Config.Bias_Threshold_Top \
                            and commodity_future_date_contract_data.bias5 >= Robot8Config.Bias_Threshold_Bottom:
                        bull_short_line = commodity_future_date_contract_data.ma5
                    if bull_short_line == None:
                        # 如果最后任何bias指标都无法确定哪一根均线可以作为牛熊线的话，则将前一个交易日的收盘价作为牛熊线。注意：现在数据库中last_close_price字段没有空值
                        bull_short_line = commodity_future_date_contract_data.last_close_price
                    if robot8_commodity_future_transaction_record.direction == Direction.Up and commodity_future_date_contract_data.close_price < bull_short_line:
                        sell_or_buy_price = commodity_future_date_contract_data.close_price
                        do_sell_or_buy = True
                    if robot8_commodity_future_transaction_record.direction == Direction.Down and commodity_future_date_contract_data.close_price >= bull_short_line:
                        sell_or_buy_price = commodity_future_date_contract_data.close_price
                        do_sell_or_buy = True

                if do_sell_or_buy == True:
                    # 平仓
                    if robot8_commodity_future_transaction_record.direction == Direction.Up:
                        # 更新robot8_c_f_transact_record表的sell_date、sell_price、sell_lot、close_commission、profit_and_loss和profit_and_loss_rate字段
                        robot8_commodity_future_transaction_record.sell_date = current_transaction_date
                        robot8_commodity_future_transaction_record.sell_price = commodity_future_date_contract_data.close_price
                        robot8_commodity_future_transaction_record.sell_lot = robot8_commodity_future_transaction_record.buy_lot
                        robot8_commodity_future_transaction_record.close_commission = FeeUtil.calculate_close_old_commodity_future_fee(
                            commodity_future_date_contract_data.close_price, commodity_future_info,
                            robot8_commodity_future_transaction_record.sell_lot)
                        robot8_commodity_future_transaction_record.profit_and_loss = float(
                            robot8_commodity_future_transaction_record.sell_price) * float(
                            robot8_commodity_future_transaction_record.sell_lot) * float(
                            commodity_future_info.transaction_multiplier) - float(
                            robot8_commodity_future_transaction_record.buy_price) * float(
                            robot8_commodity_future_transaction_record.buy_lot) * float(
                            commodity_future_info.transaction_multiplier)
                        robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                            robot8_commodity_future_transaction_record.profit_and_loss) / (float(
                            robot8_commodity_future_transaction_record.buy_price) * float(
                            robot8_commodity_future_transaction_record.buy_lot) * float(
                            commodity_future_info.transaction_multiplier) * float(
                            commodity_future_info.company_deposit)) * 100
                        # robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                        #     robot8_commodity_future_transaction_record.profit_and_loss) / float(
                        #     robot8_commodity_future_transaction_record.buy_price) / float(
                        #     commodity_future_info.company_deposit) * 100
                        self.update(robot8_commodity_future_transaction_record)
                    if robot8_commodity_future_transaction_record.direction == Direction.Down:
                        # 更新robot8_c_f_transact_record表的buy_date、buy_price、buy_lot、close_commission、profit_and_loss和profit_and_loss_rate字段
                        robot8_commodity_future_transaction_record.buy_date = current_transaction_date
                        robot8_commodity_future_transaction_record.buy_price = commodity_future_date_contract_data.close_price
                        robot8_commodity_future_transaction_record.buy_lot = robot8_commodity_future_transaction_record.sell_lot
                        robot8_commodity_future_transaction_record.close_commission = FeeUtil.calculate_close_old_commodity_future_fee(
                            commodity_future_date_contract_data.close_price, commodity_future_info,
                            robot8_commodity_future_transaction_record.buy_lot)
                        robot8_commodity_future_transaction_record.profit_and_loss = float(
                            robot8_commodity_future_transaction_record.sell_price) * float(
                            robot8_commodity_future_transaction_record.sell_lot) * float(
                            commodity_future_info.transaction_multiplier) - float(
                            robot8_commodity_future_transaction_record.buy_price) * float(
                            robot8_commodity_future_transaction_record.buy_lot) * float(
                            commodity_future_info.transaction_multiplier)
                        robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                            robot8_commodity_future_transaction_record.profit_and_loss) / (float(
                            robot8_commodity_future_transaction_record.sell_price) * float(
                            robot8_commodity_future_transaction_record.sell_lot) * float(
                            commodity_future_info.transaction_multiplier) * float(
                            commodity_future_info.company_deposit)) * 100
                        # robot8_commodity_future_transaction_record.profit_and_loss_rate = float(
                        #     robot8_commodity_future_transaction_record.profit_and_loss) / float(
                        #     robot8_commodity_future_transaction_record.sell_price) /  float(
                        #     commodity_future_info.company_deposit) * 100
                        self.update(robot8_commodity_future_transaction_record)

    def rollover_for_open(self, current_transaction_date):
        """
        移仓换月：开仓
        """

        Logger.info("移仓换月：开仓，交易日期为：" + str(current_transaction_date))

        # 获取所有账户信息
        robot8_account_queryset = Robot8Account.objects.all()
        for robot8_account in robot8_account_queryset:

            # 持有期货的数量
            hold_commodity_future_number = robot8_account.hold_commodity_future_number

            # 如果当前账户持有期货的数量已经大于等于最大持有期货数量，则查找下一个机器人账户
            if hold_commodity_future_number >= Robot8Config.Max_Holding_Comodity_Future_Number:
                Logger.info("账户[" + robot8_account.robot_name + "]持有期货数量已经是[" + str(
                    Robot8Config.Max_Holding_Comodity_Future_Number) + "]，不再开仓")
                continue

            robot8_commodity_future_rollover_queryset = Robot8CommodityFutureRollover.objects.filter(Q(robot_name=robot8_account.robot_name) & Q(
                                first_transaction_date__isnull=True) & Q(final_transaction_date__lt=current_transaction_date))
            if robot8_commodity_future_rollover_queryset != None and len(robot8_commodity_future_rollover_queryset) != 0:
                for robot8_commodity_future_rollover in robot8_commodity_future_rollover_queryset:

                    commodity_future_date_contract_data_queryset = CommodityFutureDateContractData.objects.filter(
                        Q(transaction_date=current_transaction_date) & Q(code=robot8_commodity_future_rollover.code))
                    if commodity_future_date_contract_data_queryset == None or len(commodity_future_date_contract_data_queryset) == 0:
                        Logger.info("期货[" + robot8_commodity_future_rollover.code + "]在日期[" + str(current_transaction_date) + "]没有交易记录，跳过")
                        continue
                    commodity_future_date_contract_data = commodity_future_date_contract_data_queryset[0]
                    commodity_future_info = CommodityFutureInfo.objects.get(code=robot8_commodity_future_rollover.code)

                    # 如果新合约的第一个交易日和上一个合约的最后一个交易日的filter_type不一致，则删除
                    continue_rollover = True
                    if robot8_commodity_future_rollover.filter_type == 1 and commodity_future_date_contract_data.dif < commodity_future_date_contract_data.dea:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 2 and commodity_future_date_contract_data.dif > commodity_future_date_contract_data.dea:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 3 and commodity_future_date_contract_data.close_price < commodity_future_date_contract_data.ma5:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 4 and commodity_future_date_contract_data.close_price > commodity_future_date_contract_data.ma5:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 5 and commodity_future_date_contract_data.ha_close_price < commodity_future_date_contract_data.ha_open_price:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 6 and commodity_future_date_contract_data.ha_close_price > commodity_future_date_contract_data.ha_open_price:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 7 and commodity_future_date_contract_data.k < commodity_future_date_contract_data.d:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 8 and commodity_future_date_contract_data.k > commodity_future_date_contract_data.d:
                        continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 9:
                        # 牛熊线
                        bull_short_line = None
                        if commodity_future_date_contract_data.ma250 != None and commodity_future_date_contract_data.bias250 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias250 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma250
                        if commodity_future_date_contract_data.ma120 != None and commodity_future_date_contract_data.bias120 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias120 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma120
                        if commodity_future_date_contract_data.ma60 != None and commodity_future_date_contract_data.bias60 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias60 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma60
                        if commodity_future_date_contract_data.ma20 != None and commodity_future_date_contract_data.bias20 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias20 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma20
                        if commodity_future_date_contract_data.ma10 != None and commodity_future_date_contract_data.bias10 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias10 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma10
                        if commodity_future_date_contract_data.ma5 != None and commodity_future_date_contract_data.bias5 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias5 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma5
                        if bull_short_line == None:
                            # 如果最后任何bias指标都无法确定哪一根均线可以作为牛熊线的话，则将前一个交易日的收盘价作为牛熊线。注意：现在数据库中last_close_price字段没有空值
                            bull_short_line = commodity_future_date_contract_data.last_close_price
                        if commodity_future_date_contract_data.close_price < bull_short_line:
                            continue_rollover = False
                    if robot8_commodity_future_rollover.filter_type == 10:
                        # 牛熊线
                        bull_short_line = None
                        if commodity_future_date_contract_data.ma250 != None and commodity_future_date_contract_data.bias250 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias250 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma250
                        if commodity_future_date_contract_data.ma120 != None and commodity_future_date_contract_data.bias120 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias120 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma120
                        if commodity_future_date_contract_data.ma60 != None and commodity_future_date_contract_data.bias60 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias60 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma60
                        if commodity_future_date_contract_data.ma20 != None and commodity_future_date_contract_data.bias20 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias20 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma20
                        if commodity_future_date_contract_data.ma10 != None and commodity_future_date_contract_data.bias10 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias10 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma10
                        if commodity_future_date_contract_data.ma5 != None and commodity_future_date_contract_data.bias5 <= Robot8Config.Bias_Threshold_Top \
                                and commodity_future_date_contract_data.bias5 >= Robot8Config.Bias_Threshold_Bottom:
                            bull_short_line = commodity_future_date_contract_data.ma5
                        if bull_short_line == None:
                            # 如果最后任何bias指标都无法确定哪一根均线可以作为牛熊线的话，则将前一个交易日的收盘价作为牛熊线。注意：现在数据库中last_close_price字段没有空值
                            bull_short_line = commodity_future_date_contract_data.last_close_price
                        if commodity_future_date_contract_data.close_price > bull_short_line:
                            continue_rollover = False
                    if continue_rollover == False:
                        Robot8CommodityFutureRollover.objects.filter(id=robot8_commodity_future_rollover.id).update(finish=RolloverType.Finish)
                        Logger.info("期货[" + commodity_future_date_contract_data.code + "]新合约的filter_type和上一个合约不一致，无法继续开仓")
                        continue

                    # 更新robot8_c_f_rollover表
                    Robot8CommodityFutureRollover.objects.filter(Q(robot_name=robot8_commodity_future_rollover.robot_name) & Q(
                                code=robot8_commodity_future_rollover.code))\
                        .update(first_transaction_date=current_transaction_date, finish=RolloverType.Finish)

                    # 确定仓位
                    lot = 1
                    should_open_number = Robot8Config.Max_Holding_Comodity_Future_Number - robot8_account.hold_commodity_future_number
                    each_close_price = robot8_account.capital_assets / should_open_number
                    cost_and_fee = FeeUtil.calculate_open_commodity_future_cost_and_fee(commodity_future_date_contract_data.close_price, commodity_future_info, lot)
                    if cost_and_fee > each_close_price:
                        # 如果剩余资金连一手也买不了，则直接跳过
                        continue
                    else:
                        while cost_and_fee < each_close_price:
                            lot = lot + 1
                            cost_and_fee = FeeUtil.calculate_open_commodity_future_cost_and_fee(
                                commodity_future_date_contract_data.close_price, commodity_future_info, lot)
                        lot = lot - 1

                        # 向表commodity_c_f_transact_record中插入记录
                        commodity_future_transaction_record = Robot8CommodityFutureTransactionRecord()
                        commodity_future_transaction_record.code = robot8_commodity_future_rollover.code
                        commodity_future_transaction_record.robot_name = robot8_commodity_future_rollover.robot_name
                        commodity_future_transaction_record.filter_type = robot8_commodity_future_rollover.filter_type
                        commodity_future_transaction_record.direction = robot8_commodity_future_rollover.direction
                        if robot8_commodity_future_rollover.direction == Direction.Up:
                            commodity_future_transaction_record.buy_price = commodity_future_date_contract_data.close_price
                            commodity_future_transaction_record.buy_date = current_transaction_date
                            commodity_future_transaction_record.buy_lot = lot
                        if robot8_commodity_future_rollover.direction == Direction.Down:
                            commodity_future_transaction_record.sell_price = commodity_future_date_contract_data.close_price
                            commodity_future_transaction_record.sell_date = current_transaction_date
                            commodity_future_transaction_record.sell_lot = lot
                        self.update(commodity_future_transaction_record)

                        robot8_account.hold_commodity_future_number = robot8_account.hold_commodity_future_number - 1

    def bug_or_sell_commodity_future(self, current_transaction_date):
        """
        期货开仓
        """

        Logger.info("期货开仓，交易日期为：" + str(current_transaction_date))

        # 获取所有账户信息
        robot8_account_queryset = Robot8Account.objects.all()
        for robot8_account in robot8_account_queryset:

            # 持有期货的数量
            hold_commodity_future_number = robot8_account.hold_commodity_future_number

            # 如果当前账户持有期货的数量已经大于等于最大持有期货数量，则查找下一个机器人账户
            if hold_commodity_future_number >= Robot8Config.Max_Holding_Comodity_Future_Number:
                Logger.info("账户[" + robot8_account.robot_name + "]持有期货数量已经是[" + str(
                    Robot8Config.Max_Holding_Comodity_Future_Number) + "]，不再开仓")
                continue

            # 如果是牛熊线算法，则按照顾方差降序排列，否则按照成功率降序排列
            if Robot8Config.Transaction_Strategy == 4:
                robot8_commodity_future_filter_queryset = Robot8CommodityFutureFilter.objects.all().order_by("-variance")
            else:
                robot8_commodity_future_filter_queryset = Robot8CommodityFutureFilter.objects.all().order_by("-success_rate")

            if robot8_commodity_future_filter_queryset == None or robot8_commodity_future_filter_queryset.count() == 0:
                Logger.info("表robot8_stock_filter为空，这一天没有可以进行交易的期货。退出方法")
                # 说明这一天没有可以进行交易的期货
                break
            else:
                for robot8_commodity_future_filter in robot8_commodity_future_filter_queryset:
                    # 查找这个期货的收盘价
                    close_price = CommodityFutureDateContractData.objects.values("close_price").filter(
                            Q(code=robot8_commodity_future_filter.code) & Q(
                                transaction_date=current_transaction_date)).first()['close_price']

                    # 如果期货的收盘价过高，或者资金资产太少，连一手也买不了，则直接查找下一个机器人
                    commodity_future_info = CommodityFutureInfo.objects.filter(code=CharUtil.extract_alpha(robot8_commodity_future_filter.code)).first()
                    cost_and_fee = FeeUtil.calculate_open_commodity_future_cost_and_fee(close_price, commodity_future_info, 1)
                    if cost_and_fee > robot8_account.capital_assets:
                        Logger.info("这个账户[" + robot8_account.robot_name + "]已经没有资金开仓了")
                        # 这个账户已经没有资金开仓了
                        break

                    # 如果可以开仓，则向robot8_c_f_transact_record表中插入数据，从robot8_commodity_future_filter表中删除这条记录。
                    # 计算应该开仓期货的数量
                    # robot8_commodity_future_filter表的记录数
                    robot8_commodity_future_filter_number = Robot8CommodityFutureFilter.objects.all().count()

                    # 应当开仓的期货的数量
                    should_buy_commodity_future_number = -1
                    if robot8_commodity_future_filter_number <= (Robot8Config.Max_Holding_Comodity_Future_Number - hold_commodity_future_number):
                        should_buy_commodity_future_number = robot8_commodity_future_filter_number
                    else:
                        should_buy_commodity_future_number = Robot8Config.Max_Holding_Comodity_Future_Number - hold_commodity_future_number

                    # 判断是否需要继续开仓
                    if should_buy_commodity_future_number == 0:
                        Logger.info("账号[" + robot8_account.robot_name + "]持有期货的数量已经是" + str(
                            hold_commodity_future_number) + "，不再需要开仓期货")
                        break

                    # 计算开仓多少期货
                    # 开仓多少期货（手）
                    buy_or_sell_lot = 1

                    cost_and_fee = FeeUtil.calculate_open_commodity_future_cost_and_fee(close_price, commodity_future_info, buy_or_sell_lot)
                    while robot8_account.capital_assets / (Robot8Config.Max_Holding_Comodity_Future_Number - hold_commodity_future_number) >= cost_and_fee:
                        cost_and_fee = FeeUtil.calculate_open_commodity_future_cost_and_fee(close_price, commodity_future_info, buy_or_sell_lot)
                        if cost_and_fee >= robot8_account.capital_assets / (Robot8Config.Max_Holding_Comodity_Future_Number - hold_commodity_future_number):
                            break

                        buy_or_sell_lot = buy_or_sell_lot + 1

                    cost_and_fee = FeeUtil.calculate_open_commodity_future_cost_and_fee(close_price, commodity_future_info, buy_or_sell_lot)
                    if robot8_account.capital_assets / (Robot8Config.Max_Holding_Comodity_Future_Number - hold_commodity_future_number) < cost_and_fee:
                        # 判断这个账户是否连一手都无法开仓
                        if buy_or_sell_lot == 1:
                            # 从robot8_commodity_future_filter表中删除这条记录
                            Robot8CommodityFutureFilter.objects.filter(code=robot8_commodity_future_filter.code).delete()

                            continue
                        else:
                            buy_or_sell_lot = buy_or_sell_lot - 1

                    # 向robot8_c_f_transact_record表中插入数据
                    robot8_commodity_future_transaction_record = Robot8CommodityFutureTransactionRecord()
                    robot8_commodity_future_transaction_record.robot_name = robot8_account.robot_name
                    robot8_commodity_future_transaction_record.code = robot8_commodity_future_filter.code
                    if robot8_commodity_future_filter.direction == Direction.Up:
                        robot8_commodity_future_transaction_record.buy_date = current_transaction_date
                        robot8_commodity_future_transaction_record.buy_price = close_price
                        robot8_commodity_future_transaction_record.buy_lot = buy_or_sell_lot
                    if robot8_commodity_future_filter.direction == Direction.Down:
                        robot8_commodity_future_transaction_record.sell_date = current_transaction_date
                        robot8_commodity_future_transaction_record.sell_price = close_price
                        robot8_commodity_future_transaction_record.sell_lot = buy_or_sell_lot
                    robot8_commodity_future_transaction_record.filter_type = robot8_commodity_future_filter.filter_type
                    robot8_commodity_future_transaction_record.direction = robot8_commodity_future_filter.direction
                    robot8_commodity_future_transaction_record.open_commission = FeeUtil.calculate_open_commodity_future_fee(close_price, commodity_future_info, buy_or_sell_lot)
                    self.save(robot8_commodity_future_transaction_record)

                    # 计算这支期货的持有数量、资金资产
                    robot8_account.hold_commodity_future_number = robot8_account.hold_commodity_future_number + 1
                    hold_commodity_future_number = hold_commodity_future_number + 1
                    cost_and_fee = FeeUtil.calculate_open_commodity_future_cost_and_fee(close_price, commodity_future_info, buy_or_sell_lot)
                    robot8_account.capital_assets = float(robot8_account.capital_assets) - float(cost_and_fee)

                    # 从robot8_commodity_future_filter表中删除这条记录
                    Robot8CommodityFutureFilter.objects.filter(code=robot8_commodity_future_filter.code).delete()
